<template>
    <div class="page">
        <div>
            <!-- 搜索 -->
            <isSearch :ontransType="route.query.transType" @listen="onFilter" />
            <div class="boxContent">
                <div class="timeFilter" @click="showDatePicker">
                    <div style="text-align: right">{{ date }}</div>
                    <img src="@/assets/selectIcon.png" />
                </div>
                <div class="dataBox">
                    <div class="allSum">
                        <div class="sumItem">
                            <div class="allJyNum">{{ totlaInfo.totalAmount }}</div>
                            <div class="allJyText">总交易金额(元)</div>
                        </div>
                        <div class="sumItem">
                            <div class="allJyNum">{{ totlaInfo.totalCount }}</div>
                            <div class="allJyText">总交易笔数(笔)</div>
                        </div>
                    </div>
                    <div class="dataList">
                        <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
                            <div class="listItem" v-for="(item, index) in list" :key="index">
                                <!-- 头像   -->
                                <div class="tx" v-if="item.TRANS_TYPE == 'POS_CREDIT'">贷</div>
                                <div class="tx" v-else-if="item.TRANS_TYPE == 'POS_DEBIT'">借</div>
                                <div class="tx" v-else-if="item.TRANS_TYPE == 'POS_FLASH'">云</div>
                                <div class="tx" v-else-if="item.TRANS_TYPE == 'WXPAY'">微</div>
                                <div class="tx" v-else-if="item.TRANS_TYPE == 'ALIPAY'">支</div>
                                <div class="tx" v-else-if="item.TRANS_TYPE == 'UNIONPAY'">银</div>
                                <!-- <div class="tx" v-else-if="item.TRANS_TYPE == 'VIP'">V</div> -->
                                <div class="itemInfo">
                                    <div class="titleModel">
                                        <text class="type" v-if="item.TRANS_TYPE == 'POS_CREDIT'">贷记卡刷卡</text>
                                        <text class="type" v-else-if="item.TRANS_TYPE == 'POS_DEBIT'">借记卡刷卡</text>
                                        <text class="type" v-else-if="item.TRANS_TYPE == 'POS_FLASH'">云闪付</text>
                                        <text class="type" v-else-if="item.TRANS_TYPE == 'WXPAY'">微信扫码</text>
                                        <text class="type" v-else-if="item.TRANS_TYPE == 'ALIPAY'">支付宝扫码</text>
                                        <text class="type" v-else-if="item.TRANS_TYPE == 'UNIONPAY'">银联扫码</text>
                                        <!-- <text class="type" v-else-if="item.TRANS_TYPE == 'VIP'">VIP</text> -->
                                        <text class="moneyNum">-{{ item.AMOUNT }}</text>
                                    </div>
                                    <div class="row">
                                        <div class="type">交易SN:</div>
                                        <div class="moneyNum">
                                            <span>{{ item.TUSN }}</span>
                                            <img @click="onCopy(item.TUSN)" class="isCopy" src="@/assets/icon/copy.png" />
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="type">交易单号:</div>
                                        <div class="moneyNum">
                                            <span>{{ item.FLOW_ID }}</span>
                                            <img @click="onCopy(item.FLOW_ID)" class="isCopy" src="@/assets/icon/copy.png" />
                                        </div>
                                    </div>
                                    <div class="row">
                                        <span><text class="type">交易时间:</text></span>
                                        <text class="moneyNum">{{ formatTime(item.CREATE_TIME) }}</text>
                                    </div>
                                </div>
                            </div>
                        </van-list>
                    </div>
                </div>
            </div>
        </div>
        <van-calendar
            :allow-same-day="true"
            :min-date="minDate"
            :max-date="maxDate"
            color="#55bbf9"
            v-model:show="showDay"
            :default-date="defaultDay"
            :show-confirm="false"
            type="range"
            @confirm="onConfirm"
        >
            <template #footer>
                <div class="footer">
                    <div class="item" @click="getDay('上周', 'date')">
                        <van-button type="primary">上周</van-button>
                    </div>
                    <div class="item" @click="getDay('本周', 'date')">
                        <van-button type="primary">本周</van-button>
                    </div>
                    <div class="item" @click="getDay('上月', 'date')">
                        <van-button type="primary">上月</van-button>
                    </div>
                    <div class="item" @click="getDay('本月', 'date')">
                        <van-button type="primary">本月</van-button>
                    </div>
                </div>
            </template>
        </van-calendar>
    </div>
</template>

<script setup>
import isSearch from './component/search.vue'
import { findTradeDetailByPage, findTradeTotal } from '@/api/merchants'
import { showToast } from 'vant'
import { parseTime } from '@/utils/utils.ts'

const showDay = ref(false)
const defaultDay = ref([])
const list = ref([])
const filterParams = ref({})
const totlaInfo = ref({})

const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const finished = ref(false)
const route = useRoute()

// 日历设置选择范围(去年今天-至今)
// 格式化日期格式
const formatDate = date =>
    `${date.getFullYear()}-${date.getMonth() + 1 >= 10 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1)}-${
        date.getDate() >= 10 ? date.getDate() : '0' + date.getDate()
    }`
const minDate = ref(new Date(new Date().getFullYear() - 1, new Date().getMonth() + 1, new Date().getDate()))
const maxDate = ref(new Date(new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate()))
// 初始日期默认为当天
const date = ref(`${formatDate(new Date())}至${formatDate(new Date())}`)

const onConfirm = values => {
    console.log(values)
    const [start, end] = values
    showDay.value = false
    date.value = `${formatDate(start)} 至 ${formatDate(end)}`
    currentPage.value = 1
    getList(1)
    tradeTotal()
}
const showDatePicker = () => {
    showDay.value = true
}
const getList = val => {
    // 获取列表数据
    findTradeDetailByPage({
        customerNo: route.query.CUSTOMER_NO,
        currentPage: currentPage.value,
        pageSize: pageSize.value,
        ...filterParams.value,
        startTime: date.value.split('至')[0],
        endTime: date.value.split('至')[1]
    }).then(res => {
        // 是1为筛选
        if (val == 1) {
            list.value = res.object.list
        } else {
            list.value.push(...res.object.list)
        }
        loading.value = false
        if (res.object.list.length < 10) {
            finished.value = true
        } else {
            finished.value = false
        }
    })
}
const getDay = (dayType, key) => {
    var today = new Date()
    if (dayType === '本周') {
        // 获取当前日期
        // 获取今天是星期几（0 表示星期日，1 表示星期一，以此类推）
        var dayOfWeek = today.getDay()
        // 计算星期一距离今天的天数
        var daysUntilMonday = 1 - dayOfWeek
        // 计算星期一的日期
        var monday = new Date(today)
        monday.setDate(today.getDate() + daysUntilMonday)
        console.log('本周星期一的日期是：' + parseTime(monday.toDateString(), '{y}-{m}-{d}'))
        if (key === 'date') {
            date.value = `${parseTime(monday.toDateString(), '{y}-{m}-{d}')}至${parseTime(new Date(), '{y}-{m}-{d}')}`
            defaultDay.value = [monday, new Date()]
        }
    }
    if (dayType === '本月') {
        // 获取当前月份的第一天
        var firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1)
        // 输出本月第一天的日期
        console.log('本月的第一天是：' + parseTime(firstDayOfMonth.toDateString(), '{y}-{m}-{d}'))
        if (key === 'date') {
            date.value = `${parseTime(firstDayOfMonth.toDateString(), '{y}-{m}-{d}')}至${parseTime(new Date(), '{y}-{m}-{d}')}`
            defaultDay.value = [firstDayOfMonth, new Date()]
        }
    }
    if (dayType === '上周') {
        // 获取今天是星期几（0 表示星期日，1 表示星期一，以此类推）
        var dayOfWeek = today.getDay()
        // 计算上周星期一距离今天的天数
        var daysUntilLastMonday = dayOfWeek + 6 // 加 6 天是因为今天也算一天
        // 计算上周星期一的日期
        var lastMonday = new Date(today)
        lastMonday.setDate(today.getDate() - daysUntilLastMonday)

        // 获取今天是星期几（0 表示星期日，1 表示星期一，以此类推）
        var dayOfWeek1 = today.getDay()

        // 计算上周星期日距离今天的天数
        var daysUntilLastSunday = dayOfWeek1

        // 计算上周星期日的日期
        var lastSunday = new Date(today)
        lastSunday.setDate(today.getDate() - daysUntilLastSunday)
        // 调整日期到上周
        lastSunday.setDate(lastSunday.getDate())

        // 输出上周星期一的日期
        console.log('上周星期一的日期是：' + parseTime(lastMonday.toDateString()))
        // 输出上周星期日的日期
        console.log('上周星期日的日期是：' + parseTime(lastSunday.toDateString()))

        if (key === 'date') {
            date.value = `${parseTime(lastMonday.toDateString(), '{y}-{m}-{d}')}至${parseTime(lastSunday.toDateString(), '{y}-{m}-{d}')}`
            defaultDay.value = [lastMonday, lastSunday]
        }
    }
    if (dayType === '上月') {
        // 获取上个月的年份和月份
        var lastMonthYear = today.getFullYear()
        var lastMonth = today.getMonth() - 1

        // 如果当前月份是一月，需要减少年份，并设置月份为十二月
        if (lastMonth < 0) {
            lastMonthYear -= 1
            lastMonth = 11 // JavaScript 月份是从0开始，十二月是11
        }

        // 获取上个月的第一天（1号）
        var firstDayOfLastMonth = new Date(lastMonthYear, lastMonth, 1)

        // 获取本月的第一天（1号）
        var firstDayOfThisMonth = new Date(today.getFullYear(), today.getMonth(), 1)

        // 获取上个月的最后一天（这个月的0号，即上个月的最后一天）
        var lastDayOfLastMonth = new Date(firstDayOfThisMonth)
        lastDayOfLastMonth.setDate(0)

        console.log('上个月的1号是：' + parseTime(firstDayOfLastMonth.toDateString()))
        console.log('上个月的最后一天是：' + parseTime(lastDayOfLastMonth.toDateString()))
        if (key === 'date') {
            date.value = `${parseTime(firstDayOfLastMonth.toDateString(), '{y}-{m}-{d}')}至${parseTime(
                lastDayOfLastMonth.toDateString(),
                '{y}-{m}-{d}'
            )}`
            defaultDay.value = [firstDayOfLastMonth, lastDayOfLastMonth]
        }
    }
    currentPage.value = 1
    console.log(date.value, 'date.value')
    getList(1)
    tradeTotal()
    showDay.value = false
}
const tradeTotal = () => {
    // 获交易总数居
    findTradeTotal({
        customerNo: route.query.CUSTOMER_NO,
        currentPage: currentPage.value,
        pageSize: pageSize.value,
        ...filterParams.value,
        startTime: date.value.split('至')[0],
        endTime: date.value.split('至')[1]
    }).then(res => {
        totlaInfo.value = res.object
    })
}
const onLoad = () => {
    // 异步更新数据
    currentPage.value += 1
    console.log(111, 222)
    getList(2)
}
const onFilter = val => {
    currentPage.value = 1
    filterParams.value = val
    getList(1)
    tradeTotal()
    console.log(filterParams.value, 'filterParams.value')
}
// clearSearch(val){
//     filterParams.value = val
// }

// 复制内容
const onCopy = val => {
    const copyText = val
    const input = document.createElement('input')
    input.value = copyText
    document.body.appendChild(input)
    input.select()
    document.execCommand('copy')
    document.body.removeChild(input)
    showToast('复制成功')
}
// 时间戳格式化
const formatTime = time => {
    let date = new Date(time)

    let year = date.getFullYear()

    let month = date.getMonth() + 1

    let day = date.getDate()

    let hour = date.getHours()

    let minute = date.getMinutes()

    let second = date.getSeconds()

    return (
        year +
        '-' +
        month.toString().padStart(2, '0') +
        '-' +
        day.toString().padStart(2, '0') +
        ' ' +
        hour.toString().padStart(2, '0') +
        ':' +
        minute.toString().padStart(2, '0') +
        ':' +
        second.toString().padStart(2, '0')
    )
}
watch(
    () => route.query.transType,
    newValue => {
        console.log(route.query.time, '   console.log(route.query.time)')
        filterParams.value = {
            transType: newValue
        }
        if (route.query.time == '当天') {
            getList(2)
            tradeTotal()
        } else if (route.query.time == '本月') {
            getDay('本月', 'date')
        } else if (route.query.time == '总') {
            date.value = `${route.query.startTime}至${formatDate(new Date())}`
            defaultDay.value = [new Date(route.query.startTime), new Date()]
            getList(2)
            tradeTotal()
        }
        console.log('newValue', newValue)
    },
    { immediate: true, deep: true }
)
</script>
<style scoped lang="scss">
.boxContent {
    padding: 10px 20px;
    .timeFilter {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        font-size: 14px;

        img {
            width: 10px;
            height: 10px;
            margin-left: 6px;
        }
    }
    .dataBox {
        margin-top: 20px;
        .allSum {
            display: flex;
            justify-content: space-between;
            .sumItem {
                width: 48%;
                background: #66d6ff;
                opacity: 1;
                border-radius: 8px;
                padding: 9px 15px;
                color: #fff;
                .allJyNum {
                    font-size: 16px;
                    font-family: DingTalk JinBuTi;
                    font-weight: 400;
                    color: #ffffff;
                }
                .allJyText {
                    font-size: 12px;
                    margin-top: 8px;
                }
            }
        }
        .dataList {
            margin-top: 10px;
            .listItem {
                display: flex;
                background: #fff;
                padding: 10px 16px 10px 10px;
                margin-top: 15px;
                .tx {
                    width: 32px;
                    height: 32px;
                    line-height: 32px;
                    text-align: center;
                    background: #66d6ff;
                    color: #fff;
                    border-radius: 50%;
                    margin-right: 8px;
                }
                .itemInfo {
                    flex: 1;
                    .row {
                        color: #9f9f9f;
                        margin-top: 10px;
                        font-size: 14px;
                        .moneyNum {
                            width: 70vw;
                        }
                    }
                    .titleModel {
                        display: flex;
                        justify-content: space-between;
                    }
                    .moneyNum {
                        // width: 65vw;
                        margin-top: 6px;
                        word-wrap: break-word;
                        .isCopy {
                            width: 15px;
                            height: 15px;
                            margin-left: 5px;
                        }
                    }
                }
            }
        }
    }
}
.footer {
    display: flex;
    align-items: center;
    .item {
        width: 50%;
        text-align: center;
        padding: 10px 0;
        color: #ffffff;
    }
    .van-button--primary {
        background: #eef8fe;
        color: #888;
        border: 0px;
    }
}
</style>
